//
//  PhotoPickerCollectionViewCell.swift
//  CandyDate
//
//  Created by zolobdz on 2017/10/25.
//  Copyright © 2017年 HeChao. All rights reserved.
//

import UIKit

class PhotoPickerCollectionViewCell: UICollectionViewCell {
 
    enum PhotoFillState {
        case blank
        case fill
    }
    
    typealias DeleteImageBlock = (ApplyPhotoModel) -> Void
    
    lazy var iconImageView: UIImageView = {
        let view = UIImageView(image: UIImage(resource: R.image.photo_add_icon))
        view.contentMode = .scaleAspectFill
        view.clipsToBounds = true
        return view
    }()
    
    var data: ApplyPhotoModel?
    
    var deleteImageBlock: DeleteImageBlock?
    
    lazy var placeholderImage = UIImage(resource: R.image.photo_add_icon)
    
    var photoFillState: PhotoFillState {
        return deleteButton.isHidden ? PhotoFillState.blank : PhotoFillState.fill
    }
    
    lazy var deleteButton: UIButton = {
        let view = UIButton()
        view.setImage(UIImage(resource: R.image.photo_delete_icon), for: UIControlState())
        view.addTarget(self, action: #selector(deleteButtonAction), for: .touchUpInside)
        view.isHidden = true
        view.contentMode = .center
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.white
        self.addSubview(iconImageView)
        self.addSubview(deleteButton)
        
        iconImageView.snp.remakeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        deleteButton.snp.remakeConstraints { (make) in
            make.centerX.equalTo(self.snp.right).offset(-10)
            make.centerY.equalTo(self.snp.top).offset(10)
            make.width.height.equalTo(20)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func config(_ data: ApplyPhotoModel? = nil) {
        guard data != nil else {
            iconImageView.image = placeholderImage
            deleteButton.isHidden = true
            self.data = nil
            return
        }
        self.data = data
        deleteButton.isHidden = false
        if data?.isRemote ?? false {
            iconImageView.cd_setImage(with: data?.fullPathName ?? "")
            return
        } else {
            iconImageView.image = data!.image
        }
    }
    
    @objc func deleteButtonAction() {
        if deleteImageBlock != nil && data != nil{
            deleteImageBlock!(data!)
        }
    }

}
